import {Component, Input, OnInit} from '@angular/core';
import {FormControl, Validators} from '@angular/forms';
import {ValidatorMessage} from "../api/ValidatorMessage";
import {FormDirective} from "./form.directive";

@Component({
  selector: 'gn-form-field',
  template: `
    <ng-container *ngIf="visible">
      <div class="form-title">{{title}}</div>
      <div class="form-content">
        <ng-content></ng-content>
      </div>
      <div class="form-validate">
        <span *ngFor="let validator of validators">
        <div class="ui-messages-error"
             *ngIf="form.formGroup?.controls[field].dirty
        && form.formGroup?.controls[field].enabled
        && form.formGroup?.controls[field].hasError(validator.name)">
          {{validator.message}}
        </div>
        </span>
      </div>
    </ng-container>
  `
})
export class FormFieldComponent implements OnInit {

  @Input() title: string;
  @Input() field: string;
  @Input() defaultValue: any;
  @Input() validators: Array<ValidatorMessage> = [];
  @Input() visible = true;

  constructor(public form: FormDirective) {
  }

  ngOnInit(): void {
    if (this.form.formGroup) {
      const formControl = new FormControl(null, Validators.compose(this.validators.map((value) => value.validatorFn)));
      if (this.defaultValue) {
        formControl.setValue(this.defaultValue);
      }
      this.form.formGroup.addControl(this.field, formControl);
    }
  }
}
